package com.example.jpatest.service.impl;

import com.example.jpatest.entity.*;
import com.example.jpatest.repository.EnterRepository;
import com.example.jpatest.repository.TeamRepository;
import com.example.jpatest.repository.TeamTeacherRepository;
import com.example.jpatest.service.TeamService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
import java.util.Set;

/**
 * @author czx
 */
@Service
public class TeamServiceImpl implements TeamService {
    @Autowired
    TeamRepository teamRepository;

    @Autowired
    TeamTeacherRepository teamTeacherRepository;

    @Autowired
    EnterRepository enterRepository;

    @Override
    public Team getById(Long id) {
        return teamRepository.findById(id).orElse(null);
    }

    @Override
    public Team getByName(String name) {
        return teamRepository.findByName(name).orElse(null);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveTeam(Team team) {
        teamRepository.save(team);
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public List<Team> getTeams() {
        return teamRepository.findAll();
    }


    @Override
    public Set<Student> getAllStudent(Team team) {
        return team.getStudents();
    }

    @Override
    public List<Teacher> getTeachers(Team team) {
        List<Teacher> teachers = new LinkedList<>();
        for (TeamTeacher teamTeacher : team.getTeamTeachers()) {
            Teacher teacher = teamTeacher.getTeacher();
            if (teacher != null) {
                teachers.add(teacher);
            }
        }
        return teachers;
    }

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void deleteTeam(Team team) {
        for (Enter enter : team.getEnter()) {
            team.getEnter().remove(enter);
            enterRepository.delete(enter);
        }
        for (TeamTeacher teamTeacher : team.getTeamTeachers()) {
            team.getTeamTeachers().remove(teamTeacher);
            teamTeacherRepository.delete(teamTeacher);
        }
        for (Student student : team.getStudents()) {
            if(student.getTeams().contains(team)){
                student.getTeams().remove(team);
            }
        }
        teamRepository.delete(team);
    }

    @Override
    public Set<Enter> getEnters(Team team) {
        return team.getEnter();
    }
}
